package com.hlx.project.job;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hlx.project.mapper.UserMapper;
import com.hlx.project.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hlx.project.constant.RedisConstant.*;

/**
 * 缓存预热任务
 */
@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedissonClient redissonClient;

    private List<Long> mainUserList = Arrays.asList(1L);

    @Scheduled(cron = "20 46 22 * * *")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock(USER_RECOMMEND_LOCK_KEY);
        try {
            // 只有一个线程能够获得锁  
            // wait时间为0，定时任务一天只执行一次
            // watchDog自动续费30秒:  防止宕机
            if (lock.tryLock(0, 30000L, TimeUnit.MILLISECONDS)) {
                System.out.println("getLock: " + Thread.currentThread().getId());
                for (Long userId : mainUserList) {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userMapper.selectPage(new Page<>(1, 20), queryWrapper);
                    String redisKey = USER_RECOMMEND + userId;
                    try {
                        redisTemplate.opsForValue().set(redisKey, userPage, USER_RECOMMEND_TTL, TimeUnit.SECONDS);
                    } catch (Exception e) {
                        log.error("redis set key err: ", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error: " + e);
        } finally {
            if(lock.isHeldByCurrentThread()) {
                System.out.println("unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }

    }
}
